package com.scau.yangsuiyu.estore.controller;

import com.alibaba.fastjson.JSONObject;
import com.jfoenix.controls.JFXPasswordField;
import com.jfoenix.controls.JFXTextField;
import com.scau.yangsuiyu.estore.controller.myComponent.TopSpan;
import com.scau.yangsuiyu.estore.dababases.entity.Buyer;
import com.scau.yangsuiyu.estore.dababases.entity.Seller;
import com.scau.yangsuiyu.estore.dababases.entity.User;
import com.scau.yangsuiyu.estore.service.AppService;
import com.scau.yangsuiyu.estore.service.LoginService;
import com.scau.yangsuiyu.estore.util.FormValidate;
import de.felixroske.jfxsupport.FXMLController;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.AnchorPane;

import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;

/**
 * @author suiyu_yang
 * @description 登录界面Controller
 * @date 2019-05-19 17:41
 * @email suiyu_yang@163.com
 */
@FXMLController
public class LoginController extends AnchorPane implements Initializable {
    private String loginRole = "buyer";
    private FormValidate<TextField> formValidate = new FormValidate<>();
    private TopSpan topSpan;

    @FXML
    private Label roleLabel;

    @FXML
    private Label passwordError;

    @FXML
    private Label loginKetError;

    @FXML
    private JFXTextField loginKeyTF;

    @FXML
    private JFXPasswordField passwordTF;

    @FXML
    private Button changeRoleButton;

    @FXML
    private AnchorPane topSpanContainer;

    public LoginController() {
        loadFXML();
    }

    private void loadFXML() {
        FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/view/Login.fxml"));
        fxmlLoader.setController(this);
        fxmlLoader.setRoot(this);
        try {
            fxmlLoader.load();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        topSpanContainer.getChildren().add(new TopSpan());


        TextField[] requireTFs = {passwordTF, loginKeyTF};
        Label[] reqLabels = {passwordError, loginKetError};
        passwordError.setText("密码栏不能为空");
        loginKetError.setText("用户名不能为空");
        formValidate.installRequireValidation(requireTFs, reqLabels);


        loginKeyTF.setOnKeyPressed(new EventHandler<KeyEvent>() {
            @Override
            public void handle(KeyEvent event) {
                if (event.getCode() == KeyCode.ENTER) {
                    login();
                }
            }
        });
        passwordTF.setOnKeyPressed(new EventHandler<KeyEvent>() {
            @Override
            public void handle(KeyEvent event) {
                if (event.getCode() == KeyCode.ENTER) {
                    login();
                }
            }
        });
    }

    @FXML
    private void changeRole() {
        if (loginRole.equals("buyer")) { //此时应为买家登录，切换后应为"卖家登录"
            roleLabel.setText("卖家登录");

            loginRole = "seller";
            changeRoleButton.setText("我是买家");

        } else { //此时应为卖家登录，切换后应为"买家登录"
            roleLabel.setText("买家登录");

            changeRoleButton.setText("我是卖家");
            loginRole = "buyer";

        }
    }

    @FXML
    private void login() {
        passwordError.setText("");
        JSONObject loginJson = new JSONObject();

        String loginKey = loginKeyTF.getText();
        String password = passwordTF.getText();

        if (formValidate.isValid()) {

            loginJson.put("role", loginRole);
            loginJson.put("key", loginKey);
            loginJson.put("password", password);

            JSONObject resultJson = new LoginService().login(loginJson);
            if (resultJson.get("status").equals("success")) {
                User user;
                if (loginRole.equals("buyer")) {
                    user = resultJson.getObject("user", Buyer.class);
                    gotoIndex(user);
                } else {
                    user = resultJson.getObject("user", Seller.class);
                    gotoUserLayout(user);
                }

            } else {
                passwordError.setVisible(true);
                passwordError.setText(resultJson.getString("result"));
            }
        }
    }

    private void gotoUserLayout(User user) {
        new AppService().closeCurrentTab();

        JSONObject userJson = new JSONObject();
        userJson.put("user", user);

        if (user instanceof Seller) {
            new AppService().gotoSellerLayout(userJson);
        } else if (user instanceof Buyer) {
            new AppService().gotoBuyerLayout(userJson);
        }

    }

    private void gotoIndex(User user) {
        new AppService().closeCurrentTab();

        new AppService().gotoIndexPage(user);
    }

    @FXML
    private void gotoRegister() {
        new AppService().gotoRegister();
    }
}
